package com.gs.synedocket.activity.base;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.gs.synedocket.R;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.presenter.BasePresenter;
import com.gs.synedocket.util.LanguageUtils;
import com.gs.synedocket.util.WindowUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public abstract class BaseActivity<V, T extends BasePresenter<V>> extends BaseTouchActivity {
    protected T mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        EventBus.getDefault().register(this);
        WindowUtil.getInstance().setBarBgColor(this, R.color.bar_color);
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);
        }
        initView();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LanguageUtils.getInstance().change(LanguageUtils.getInstance().getCurrentLanguage()));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_LANGUAGE) {
            LanguageUtils.getInstance().change(LanguageUtils.getInstance().getCurrentLanguage());
            recreate();
        } else if (event.getWhat() == EventCode.EVENT_SITE) {
            recreate();
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract T createPresenter();

    protected <I extends View> I fd(int id) {
        return findViewById(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
